import { searchEntList } from '@/api/codeServer'
import { usePagination } from 'ahooks'
import { Checkbox, Pagination, Spin } from 'antd'
import { useEffect, useImperativeHandle, useMemo, useState } from 'react'
import { selectListObj } from './ChoiceCompany'

interface ListProps {
  innerRef: React.MutableRefObject<any>
  filter: boolean
  searchVal: string
  defaultValue?: string[]
  associationId?: string
  onChange?(value: { idList: string[]; list: selectListObj[] }): void
}

export const PersonList = ({
  innerRef,
  searchVal,
  filter,
  defaultValue,
  associationId,
  onChange
}: ListProps) => {
  //定义列表数据
  const [list, setList] = useState<selectListObj[]>([])
  //定义选中的数据
  const [selectList, setSelectList] = useState<selectListObj[]>([])
  const [selectIdList, setSelectIdList] = useState<string[]>([])
  //全选
  // const [selectAllbtn, setSelectAllbtn] = useState<boolean>(false)

  const selectAllbtn = useMemo(() => {
    let n = 0
    list.forEach((v) => {
      n++
    })
    return selectIdList.length > 0 && selectIdList.length === n
  }, [list, selectIdList])

  const selectAll = () => {
    if (selectAllbtn) {
      // 显示区域内的全部取消
      setSelectIdList([...[]])
      setSelectList([...[]])
      // setSelectAllbtn(false)
    } else {
      // 显示内的全部选中
      list.forEach((v) => {
        if (!selectIdList.includes(v.entId)) {
          selectIdList.push(v.entId)
          selectList.push(v)
        }
      })
      setSelectIdList([...selectIdList])
      setSelectList([...selectList])
      // setSelectAllbtn(true)
    }
  }

  const toastTip = function (item: selectListObj) {
    return true
  }
  //选择
  const clickItem = (item: selectListObj) => {
    const canChoise = toastTip(item)
    if (!canChoise) {
      return
    }
    const index = selectIdList.indexOf(item.entId)
    if (index === -1) {
      selectIdList.push(item.entId)
      selectList.push(item)
    } else {
      selectIdList.splice(index, 1)
      selectList.splice(index, 1)
    }
    setSelectIdList([...selectIdList])
    setSelectList([...selectList])
  }

  const { data, loading, pagination, run } = usePagination(
    async ({ current, pageSize }) => {
      const { list = [], total = 0 } = await searchEntList({
        pageSize,
        pageIndex: current,
        entName: searchVal,
        associationId
      })
      return {
        list,
        total
      }
    }
  )

  //初始化
  // useMount(() => {
  //   simpleListPersonList({
  //     entId: 'xxx',
  //     keyWords: searchVal
  //     // associationId,
  //     // filter,
  //     // pageSize,
  //     // pageIndex
  //   }).then((data) => {
  //     setSpining(false)
  //     console.log(data, 'datadatadata')
  //     const aaadata = [
  //       {
  //         entId: 'd0d1b81f37f243c28008277a4d61c2d9',
  //         name: 'ssss',
  //         icon: defPic
  //       },
  //       {
  //         entId: '465b8496d5b846269fd9ce8d566f0417',
  //         name: 'asss',
  //         icon: defPic
  //       }
  //     ]
  //     setList(data)
  //     if (defaultValue?.length) {
  //       data.forEach((v) => {
  //         if (defaultValue.includes(v.entId)) {
  //           selectIdList.push(v.entId)
  //           selectList.push(v)
  //           setSelectIdList([...selectIdList])
  //           setSelectList([...selectList])
  //         }
  //       })
  //     }
  //   })
  // })

  //监听 计算全选状态值
  // useMemo(() => {
  //   const n = list.reduce((a, b) => {
  //     return a + Number(selectIdList.includes(b.personId))
  //   }, 0)
  //   const isSelect =
  //     selectIdList.length > 0 && selectIdList.length === list.length
  //   setSelectAllbtn(isSelect)
  // }, [list, selectIdList])

  useEffect(() => {
    onChange && onChange({ idList: selectIdList, list: selectList })
  }, [selectIdList])

  //移除
  const removeItem = (item: selectListObj) => {
    const index = selectIdList.indexOf(item.entId)
    selectIdList.splice(index, 1)
    selectList.splice(index, 1)
    setSelectIdList([...selectIdList])
    setSelectList([...selectList])
  }

  //给外部调的
  useImperativeHandle(innerRef, () => ({
    getList: () =>
      run({
        current: 1,
        pageSize: pagination?.pageSize
      }),
    removeItem
  }))
  return (
    <>
      <div>
        <div className="mian-list">
          {/* <div className="checkAll-box">
            <span
              className="checkAll-item"
              onClick={() => {
                selectAll()
              }}
            >
              <Checkbox
                checked={selectAllbtn}
                defaultChecked={false}
              ></Checkbox>
              <span style={{ cursor: 'pointer', marginLeft: 6 }}>
                全选
                {selectAllbtn}
              </span>
            </span>
          </div> */}
          <ul className="list" style={{ height: '302px' }}>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              {loading ? <Spin size="large" spinning={true}></Spin> : null}
            </div>
            {data?.list.map((y, i) => {
              return (
                <li key={i} className="list-item">
                  <div
                    className="p-checkli"
                    onClick={() => {
                      clickItem(y)
                    }}
                    style={{ width: '100%', justifyContent: 'start' }}
                  >
                    <Checkbox
                      checked={selectIdList && selectIdList.includes(y.entId)}
                    ></Checkbox>
                    {/* <img className="head-icon" src={defPic} alt="icon" /> */}
                    <span className="item-name item-pname" title={y.name}>
                      {y.name}
                    </span>
                    {/* <span className="text-center">({y.phone})</span> */}
                  </div>
                </li>
              )
            })}
          </ul>
        </div>
      </div>
      <Pagination
        current={pagination.current}
        pageSize={pagination.pageSize}
        total={data?.total}
        onChange={pagination.onChange}
        size="small"
        onShowSizeChange={pagination.onChange}
        showLessItems
        showSizeChanger
        style={{ marginTop: 16, textAlign: 'right' }}
      />
    </>
  )
}
